import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactEcharts from 'echarts-for-react';

import { COLOR_LIST } from '@/utils/constants';
import { subscribeComp } from '@/services/bajaService';

class EchartsPie extends Component {

  static defaultProps = {
    title: '',
    fontSize: '16px',
    ring: false
  }

  constructor(props) {
    super(props);
    const {title, fontSize, legends, data, ring} = this.props;
    this.option = this.buildOption(title, parseInt(fontSize), legends, data, ring);
    this.subs = [];
  }

  buildOption = (title, fontSize, legends, data, ring) => ({
    title: {
      text: title,
      left: 'center',
      textStyle: {
        color: 'white',
        fontSize
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b} : {c} ({d}%)',
      extraCssText: 'width:180px; height:60px; background:#rgba(0,0,0,0.5);'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        color: 'white',
        fontSize: fontSize*0.8,
      },
      data: legends
    },
    series: [{
      type: 'pie',
      title: title,
      radius: [ring?'35%':'0%', '70%'],
      center: ['50%', '60%'],
      data: data,
      itemStyle: {
        color: params => COLOR_LIST[params.dataIndex],
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)',
      },
      emphasis: {
        label: {
          fontSize: fontSize*0.8,
        }
      }
    }]
  })

  updateChart = (value, componentName) => {
    const { data } = this.option.series[0];
    data.forEach((item) => {
      if (item.ord.endsWith("/" + componentName)) {
        item.value = value;
      }
    });
    if(this.echarts) {
      this.echarts.getEchartsInstance().setOption(this.option);
    }
  }

  subscribeChart = () => {
    this.props.data.forEach((item)=> {
      subscribeComp(item.ord, (component)=>{
        const value = parseFloat(component.getOut().getValue().toFixed(2));
        this.updateChart(value, component.getName());
      }).then((sub)=> {
        this.subs.push(sub);
      });
    });
  }

  componentDidMount() {
    this.subscribeChart();
  }

  componentWillUnmount() {
    this.subs.forEach((sub)=>{
      sub.unsubscribeAll();
      sub.detach();
    });
  }

  render() {
    return (
      <ReactEcharts
        ref={(e) => { this.echarts = e; }}
        notMerge={true}
        lazyUpdate={true}
        option={this.option}
        style={{width: '100%',height:'100%'}}
      />
    );
  }
}

EchartsPie.propTypes = {
  title: PropTypes.string,
  fontSize: PropTypes.string,
  legends: PropTypes.array.isRequired,
  data: PropTypes.array.isRequired
}

export default EchartsPie;
